import { Event, Slot, Stage, overrideFinally } from './engine.js';
import {auv, zhi, sagi, hei, tang, yi, teacher, EW } from './init.js';
import {sagiMini1Show, sagiMini1FailShow, zhiKfcShow, zhiKfcFailShow, 
  sagiMini2Show, sagiMini2FailShow, sagiAfternoonShow, sagiMini2StopSchoolShow, zhiAfterSchoolShow, zhiAfterSchoolFailShow, morningTeaShow,
  yiDelta1Show, yiDelta2Show,
  halloweenSameShow, halloweenZhiShow, halloweenSagiShow, halloweenHeiShow, halloweenCatchShow, tangHomeMiniShow, 
  lunchSickSameShow, lunchSickArkShow, lunchSickHeiShow, lunchSickNoneShow, ark1Show, ark2Show, auvConfessionEWShow, heiYi1Show } from './plot.js';
import { getSleepSettlementShow } from './settlement.js';

// 事件1：认真听专业课
const techClassEvent = new Event(
  // unlockFunc
  () => auv.getStamina() >= 2,
  // decisionFunc
  () => true,
  // yesEventBody
  () => {
    // -Stamina，+auv的tech
    auv.changeStamina(-5); // 增加消耗
    auv.attrs.tech += 3; // +auv的tech
    alert('感觉自己的技术提升了！');
  },
  // noEventBody
  () => {
    // 无操作
  }
);

// 事件2：摸鱼
const slackOffEvent = new Event(
  // unlockFunc
  () => true,
  // decisionFunc
  () => true,
  // yesEventBody
  () => {
    // 小幅+Stamina
    auv.changeStamina(2); // 减少恢复量
    alert('感觉自己的精力恢复了一些！');
  },
  // noEventBody
  () => {}
);

// 事件3：与sagi讨论项目
const sagiMini1Event = new Event(
  // unlockFunc
  () => {
    // sagi的affinity不能太低，jealousy不能太高
    return (sagi.affinity) >= 15 && (sagi.jealousy) <= 30;
  },
  // decisionFunc
  () => {
    // auv的mana>=3
    return auv.attrs.mana >= 5;
  },
  // yesEventBody
  async () => {
    await window.playShow(sagiMini1Show);
    // 增加sagi的ProjectProgress和Affinity
    sagi.projectProgress += 10;
    sagi.affinity += 5;
    zhi.jealousy += 10;
  },
  // noEventBody
  async () => {
    await window.playShow(sagiMini1FailShow);
    sagi.affinity -= 3;
  }
);

const slotListenClass = new Slot('认真听课', [techClassEvent]);
const slotWatchSagi = new Slot('看同桌sagi在干嘛', [sagiMini1Event]);
const getSlotSlackOff = () => new Slot('摸鱼', [slackOffEvent]);

// 上午课堂 Stage
const morningClassroom = new Stage('上午课堂', '老师在讲计算机网络……','./教室.jpg',
      () => {
        window.playStage(lunchBreak);
      },
      [slotListenClass, slotWatchSagi, getSlotSlackOff()]
);


// 事件：找至要KFC
const zhiKfcEvent = new Event(
  // unlockFunc
  () => true,
  // decisionFunc
  () => {
    // zhi的jealousy不能太高
    return zhi.jealousy < 20 && zhi.affinity >= 40;
  },
  // yesEventBody
  async () => {
    await window.playShow(zhiKfcShow);
    // 给zhi的Affinity +1，auv+大量Stamina
    zhi.affinity += 3;
    auv.changeStamina(10); // 大量Stamina
    alert('感觉自己的精力恢复了很多！');
  },
  // noEventBody
  async () => {
    await window.playShow(zhiKfcFailShow);
  }
);

// 事件：午餐
const lunchEvent = new Event(
  // unlockFunc
  () => auv.getCash() >= 10,
  // decisionFunc
  () => Math.random() < 0.25,
  // yesEventBody
    async () => {
      //午餐事故
      auv.changeCash(-10);
      await window.playShow(lunchSickSameShow);
      //保险结算
      const insurance = auv.getInsurance();
      if(insurance > 0) {
        auv.useInsurance();
        alert(`由于之前购买了${insurance}份保险，保险公司赔付了你${insurance * 2000}，现在钱包里有了${auv.getCash()}`);
      }
      //付钱事件
      const bArkPay = auv.getArkLv() >= 50;
      const bHeiPay = hei.affinity >= 65;
      //如果两个都满足，随机用一个渠道付钱
      if(bArkPay && bHeiPay) {
        if(Math.random() < 0.5) {
          bArkPay = false;
        }
        else {
          bHeiPay = false;
        }
      }
      //付钱演出
      if (bArkPay) {
        await window.playShow(lunchSickArkShow, false);
        EW.affinity += 10;
      }
      else if (bHeiPay) {
        await window.playShow(lunchSickHeiShow, false);
        auv.changeCash(10000);
        auv.changeCash(-1200);
        hei.affinity += 10;
      }
      else {
        await window.playShow(lunchSickNoneShow, false);
        auv.changeCash(-1200);
        zhi.affinity += 10;
      }
      zhi.affinity += 30;
      zhi.jealousy = 0;
      auv.resources.stamina = 0;
      alert(`搞完这一切已经天黑了，彻底燃尽了。钱包里还剩${auv.getCash()}`);
      overrideFinally.setFinallyFunc(goHomeFunc);
    },
  // noEventBody
  () => {
    //正常午餐
    auv.changeCash(-10);
    auv.changeStamina(5); // 中等Stamina
    alert(`花了10块买午餐，精力有所回升，钱包里还剩${auv.getCash()}`);
  }
);

// 事件：自己玩明日方舟
const aloneArkEvent = new Event(
  // unlockFunc
  () => true,
  // decisionFunc
  () => true,
  // yesEventBody
  () => {
    auv.changeStamina(1); // 减少恢复量
    auv.attrs.mana += 1;
    auv.addArkLv();
    alert("精力有一点恢复，对游戏的理解也增加了");
  },
  // noEventBody
  () => {}
);

// 事件：和EW一起玩明日方舟
const arkEvent = new Event(
  // unlockFunc
  () => EW.affinity >= 10,
  // decisionFunc
  () => EW.affinity >= 30,
  // yesEventBody
  async () => {
    await window.playShow(ark2Show);
    EW.affinity += 5;
    auv.attrs.mana += 15;
    auv.resources.arkLv += 2;
    auv.changeStamina(15);
    alert('吃了维什戴尔的营养餐，精力大大恢复了。和维什戴尔打舟后，对游戏的理解也大大增加了')
  },
  // noEventBody
  async () => {
    await window.playShow(ark1Show);
    auv.attrs.mana += 20;
    auv.resources.arkLv += 5;
    if (auv.attrs.charm < 15) {
      await window.playShow(auvConfessionEWShow, false);
      EW.affinity -= 5;
    }
    else {
      EW.affinity += 10;
    }
    alert('和维什戴尔打舟后，对游戏的理解大大增加了')
  }
);

// 事件：玩明日方舟时看到hei
const arkHeiEvent = new Event(
  // unlockFunc
  () => Math.random() < 0.3,
  // decisionFunc
  () => true,
  // yesEventBody
  async () => {
    await window.playShow(heiYi1Show);
    hei.affinity += 20;
    auv.attrs.mana += 5;
    yi.jealousy += 10;
  },
  // noEventBody
  async () => {}
);


const slotFindZhiKfc = new Slot('找至要KFC', [zhiKfcEvent]);
const slotLunch = new Slot('去食堂档口打饭（10￥）', [lunchEvent]);
const getSlotPlayArknights = () => new Slot('饿着玩明日方舟', [arkHeiEvent, arkEvent, aloneArkEvent]);

// 午休 Stage
const lunchBreak = new Stage('午休', '充满蟑螂的食堂……', './食堂.jpg',
      () => {
        window.playStage(afternoonPractice);
      },
      [slotFindZhiKfc, slotLunch, getSlotPlayArknights()]
);

const goHomeFunc = () => {
  window.playStage(backHome);
};

// 事件：逃课去找sagi
const sagiMini2Event = new Event(
  // unlockFunc
  () => {
    // sagi的affinity需要足够高
    return sagi.affinity >= 55;
  },
  // decisionFunc
  () => {
    return auv.attrs.charm >= 5;
  },
  // yesEventBody
  async () => {
    async function decisionStopSchoolEvent() {
      if (Math.random() < 0.3) {
        await window.playShow(sagiMini2StopSchoolShow, false);
        teacher.affinity -= 10;
        //数值不加那么多
        sagi.affinity -= 10;
        sagi.projectProgress -= 10;
        alert('被蜂兵直接快递回家');
        overrideFinally.setFinallyFunc(goHomeFunc);
      }
    }

    //事件基础数值
    sagi.projectProgress += 20;
    zhi.jealousy += 20;
    
    if (sagi.affinity >= 100) {
      await window.playShow(sagiAfternoonShow);
      sagi.affinity += 20;
      await decisionStopSchoolEvent();
    } else {
      await window.playShow(sagiMini2Show);
      sagi.affinity += 50;
      await decisionStopSchoolEvent();
    }
  },
  // noEventBody
  async () => {
    await window.playShow(sagiMini2FailShow);
    // 减少sagi的Affinity，但仍增加projectProgress
    sagi.projectProgress += 20;
    sagi.affinity -= 10;
    zhi.jealousy += 20;
  }
);

// 事件：认真画画
const drawEvent = new Event(
  // unlockFunc
  () => auv.getStamina() >= 5,
  // decisionFunc
  () => true,
  // yesEventBody
  () => {
    // +auv的art，-Stamina
    auv.attrs.art += 5;
    auv.changeStamina(-7); // 增加消耗
    alert('感觉自己的画技提升了！');
  },
  // noEventBody
  () => {}
);

const slotFindSagi = new Slot('逃课去楼上机房找sagi', [sagiMini2Event]);
const slotDraw = new Slot('认真画画', [drawEvent]);

// 下午实训 Stage
const afternoonPractice = new Stage('下午实训', '素描上机，老师懒洋洋的……', './机房2.jpg',
      () => window.playStage(afterSchool),
      [slotFindSagi, slotDraw, getSlotSlackOff()]
);

// 事件：程序兼职
const programPartTimeEvent = new Event(
  // unlockFunc
  () => auv.getStamina() >= 10,
  // decisionFunc
  () => {
    // AUV的tech越小返回true的概率越低，tech大于15成功率100%
    if (auv.attrs.tech >= 15) return true;
    const baseProbability = Math.min(auv.attrs.tech * 0.07, 0.9); // 基础概率
    return Math.random() < baseProbability;
  },
  // yesEventBody
  () => {
    auv.changeStamina(-10);
    // 根据tech判断
    if (auv.attrs.tech < 20) {
        auv.changeCash(50);
        alert(`你替大学生写作业，赚了50，钱包里有了${auv.getCash()}`);
      } else if (auv.attrs.tech < 35) {
        auv.changeCash(100);
        alert(`你在程序员客栈接包改前端，赚了100，钱包里有了${auv.getCash()}`);
      } else if (true) {
        auv.changeCash(150);
        alert(`你找了一个中软国际的远程外包实习，帮富士康写加班系统，赚了150，钱包里有了${auv.getCash()}`);
    }
  },
  // noEventBody
  () => {
    alert('你想替大学生写作业，结果没看懂题');
  }
);

// 事件：艺术兼职
const artPartTimeEvent = new Event(
  // unlockFunc
  () => auv.getStamina() >= 10,
  // decisionFunc
  () => {
    // AUV的art越小返回true的概率越低，art大于15成功率100%
    if (auv.attrs.art >= 20) return true;
    const baseProbability = Math.min(auv.attrs.art * 0.07, 0.9); // 基础概率
    return Math.random() < baseProbability;
  },
  // yesEventBody
  () => {
    auv.changeStamina(-10);
    // 根据art判断
    let money;
    if (auv.attrs.art < 35) {
      money = Math.floor(Math.random() * 41) + 10; // 10~50
      alert(`你在QQ空间接稿，赚了${money}`);
    } else if (auv.attrs.art < 70) {
      money = Math.floor(Math.random() * 81) + 60; // 60~140
      alert(`你在画加接稿，赚了${money}`);
    } else if (true) {
      money = Math.floor(Math.random() * 601) + 200; // 200~800
      alert(`你米画师接稿，赚了${money}`);
    }
    auv.changeCash(money);
    alert(`现在钱包里有${auv.getCash()}`);
  },
  // noEventBody
  () => {
    alert('你想去QQ空间接稿，但是没人理你');
  }
);

// 事件：蜜雪冰城摇奶茶
const milkTeaPartTimeEvent = new Event(
  // unlockFunc
  () => auv.getStamina() >= 15,
  // decisionFunc
  () => {
    // 有五分之一概率为false
    return Math.random() > 0.2;
  },
  // yesEventBody
  () => {
    auv.changeStamina(-15);
    auv.changeCash(26);
    alert(`摇了两个小时奶茶，很累，挣了26，钱包里有了${auv.getCash()}`);
    auv.attrs.charm += 5;
  },
  // noEventBody
  () => {
    auv.changeStamina(-15);
    auv.changeCash(10);
    alert(`摇了两个小时奶茶，但不小心把奶茶洒仙女身上了，被资本家扣了工资，只挣了10块，钱包里有了${auv.getCash()}`);
    auv.attrs.charm += 5;
  }
);

// 事件：等至一起回家
const zhiAfterSchoolEvent = new Event(
  // unlockFunc
  () => {
    return zhi.affinity >= 30;
  },
  // decisionFunc
  () => {
    return zhi.jealousy <= 30;
  },
  // yesEventBody
  async () => {
    await window.playShow(zhiAfterSchoolShow);
    // 增加zhi的ProjectProgress和Affinity
    zhi.projectProgress += 10;
    zhi.affinity += 5;
    sagi.jealousy += 5;
  },
  // noEventBody
  async () => {
    await window.playShow(zhiAfterSchoolFailShow);
    zhi.affinity -= 10;
  }
);

// 策划兼职事件
const gameDesignPartTimeEvent = new Event(
  // unlockFunc
  () => auv.getStamina() >= 5,
  // decisionFunc
  () => {
    // AUV的mana越小返回true的概率越低，mana大于等于20成功率100%
    if (auv.attrs.mana >= 20) return true;
    const baseProbability = Math.min(auv.attrs.mana * 0.05 + 0.1, 0.95); // 基础概率
    return Math.random() < baseProbability;
  },
  // yesEventBody
  () => {
    auv.changeStamina(-5);
    const Lv2Threshold = 70;
    // 根据mana判断
    if (auv.attrs.mana < 20) {
      auv.changeCash(10);
      alert(`你在野鸡独立游戏团队当策划，赚了10，钱包里有了${auv.getCash()}`);
    } else if (auv.attrs.mana < Lv2Threshold && auv.getArkLv() > 50) {
      auv.changeCash(120);
      alert(`你被鹰角特聘为明日方舟顾问，赚了120，钱包里有了${auv.getCash()}`);
    } else if (auv.attrs.mana < Lv2Threshold) {
      auv.changeCash(100);
      alert(`你在迷你世界社区给官方出谋划策起诉安慕希抄袭，赚了100，钱包里有了${auv.getCash()}`);
    } else if (auv.attrs.mana < 120) {
      auv.changeCash(200);
      alert(`你找了三角洲的远程策划实习，专门改爆率，赚了200，钱包里有了${auv.getCash()}`);
    }
    else if (auv.getArkLv() > 130) {
      const money = Math.floor(Math.random() * 2000); // 0~2000
      auv.changeCash(money);
      alert(`你当上了明日方舟主策，本月项目分成${money}，钱包里有了${auv.getCash()}`);
    }
    else {
      auv.changeCash(300);
      alert(`你找了王者荣耀的远程策划实习，负责给瑶出皮肤，赚了300，钱包里有了${auv.getCash()}`);
    }
  },
  // noEventBody
  () => {
    auv.changeStamina(-5);
    alert('你在野鸡独立游戏团队当策划，结果群猪跑路了，项目黄了');
  }
);

const slotProgramPartTime = new Slot('赶紧回家软件外包接单', [programPartTimeEvent]);
const slotArtPartTime = new Slot('赶紧回家接稿', [artPartTimeEvent]);
const slotGameDesignPartTime = new Slot('赶紧回家搞游戏策划', [gameDesignPartTimeEvent]);
const slotMilkTeaPartTime = new Slot('赶紧蜜雪冰城摇奶茶', [milkTeaPartTimeEvent]);
const slotWaitZhi = new Slot('等至一起回家', [zhiAfterSchoolEvent]);

// 放学后 Stage
const afterSchool = new Stage('放学后', '欢迎来到夜之城，这里没有活着的传奇，只有爱永不消逝', './放学.jpg',
      () => {
        window.playStage(backHome);
      },
      [slotProgramPartTime, slotArtPartTime, slotGameDesignPartTime, slotMilkTeaPartTime, slotWaitZhi]
);

// tangHomeMiniEvent
const tangHomeMiniEvent = new Event(
  // unlockFunc
  () => true,
  // decisionFunc
  () => true,
  // yesEventBody
  async () => {
    await window.playShow(tangHomeMiniShow);
    tang.affinity += 3;
    tang.projectProgress += 5;
  },
  // noEventBody
  () => {}
);

// 和易先生玩三角洲事件
const deltawarEvent = new Event(
  // unlockFunc
  () => true,
  // decisionFunc
  () => yi.affinity >= 30,
  // yesEventBody
  async () => {
    await window.playShow(yiDelta2Show);
    auv.attrs.mana += 5;
    yi.affinity += 10;
    alert('与易先生的时光让你对游戏的理解更深入了！');
  },
  // noEventBody
  async() => {
    await window.playShow(yiDelta1Show);
    auv.attrs.mana += 3;
    yi.affinity += 10;
    alert('与易先生的时光让你对游戏的理解更深入了！');
  }
);

// 购买保险事件
const buyInsuranceEvent = new Event(
  // unlockFunc
  () => auv.getCash() >= 30,
  // decisionFunc
  () => true,
  // yesEventBody
  () => {
    auv.changeCash(-30);
    auv.addInsurance();
    alert(`购买了医疗保险。当前有${auv.getInsurance()}份保单，钱包里还剩${auv.getCash()}`);
  },
  // noEventBody
  () => {}
);

// 直接睡觉事件
const sleepEvent = new Event(
  // unlockFunc
  () => true,
  // decisionFunc
  () => true,
  // yesEventBody
  () => {
    auv.changeStamina(7);
    alert('AUV竟然八点就躺床上了！');
  },
  // noEventBody
  () => {}
);

// 万圣节事件
const halloweenEvent = new Event(
  // unlockFunc
  () => {
    // 十分之一概率为true
    return Math.random() < 0.1;
  },
  // decisionFunc
  () => true,
  // yesEventBody
  async () => {
    // 先playShow(halloweenSameShow)
    await window.playShow(halloweenSameShow);
    let bTriggeredHeroineShow = false;
    // if zhi的affinity>50
    if (zhi.affinity > 50) {
      await window.playShow(halloweenZhiShow, false);
      auv.changeCash(7000);
      alert(`你获得了7000元，现在钱包里有${auv.getCash()}`);
      zhi.jealousy = 0;
      bTriggeredHeroineShow = true;
    }
    // if sagi的affinity>50
    if (sagi.affinity > 50) {
      await window.playShow(halloweenSagiShow, false);
      auv.resources.arkLv += 100;
      alert(`明日方舟等级上升了100，现在明日方舟等级为${auv.getArkLv()}`);
      sagi.jealousy = 0;
      bTriggeredHeroineShow = true;
    }
    // if hei的affinity>50
    if (hei.affinity > 50) {
      await window.playShow(halloweenHeiShow, false);
      auv.changeCash(500000);
      alert(`你获得了五十万元，现在钱包里有${auv.getCash()}`);
      hei.jealousy = 0;
      bTriggeredHeroineShow = true;
    }
    // 如果任意一个条件满足
    if (bTriggeredHeroineShow) {
      await window.playShow(halloweenCatchShow, false);
    }
  },
  // noEventBody
  () => {}
);

// 回家后阶段的选项槽
const slotQQSpace = new Slot('刷QQ空间', [halloweenEvent, tangHomeMiniEvent]);
const slotDeltawar = new Slot('和易先生玩三角洲', [deltawarEvent]);
const slotBuyInsurance = new Slot('购买保险（30￥）', [buyInsuranceEvent]);
const slotSleep = new Slot('直接睡觉', [sleepEvent]);

// 回家后 Stage
const backHome = new Stage('回家后', '陈电小区，巅峰住宅', './AUV家.jpg',
      async () => {
        // finallyCallback逻辑
        auv.changeStamina(20);
        await window.playShow(getSleepSettlementShow());
        window.playStage(morningSchoolGate);
      },
      [slotQQSpace, slotDeltawar, slotBuyInsurance, slotSleep]
);

// 早餐事件
const breakfastEvent = new Event(
  // unlockFunc
  () => auv.getCash() >= 5,
  // decisionFunc
  () => true,
  // yesEventBody
  () => {
    auv.changeCash(-5);
    auv.changeStamina(3);
    alert(`花了5块买早餐，精力有所回升，钱包里还剩${auv.getCash()}`);
  },
  // noEventBody
  () => {}
);

// 请至喝奶茶事件
const inviteZhiTeaEvent = new Event(
  // unlockFunc
  () => auv.getCash() >= 12,
  // decisionFunc
  () => true,
  // yesEventBody
  async () => {
    auv.changeCash(-12);
    auv.changeStamina(2);
    zhi.jealousy -= 5; // 降低至的嫉妒值
    // 播放对话
    await window.playShow(morningTeaShow);
    alert(`精力有所回升，钱包里还剩${auv.getCash()}`);
  },
  // noEventBody
  () => {}
);

const slotBreakfast = new Slot('买早餐（5￥）', [breakfastEvent]);
const slotInviteZhiTea = new Slot('请至喝奶茶（12￥）', [inviteZhiTeaEvent]);

// 早上校门口 Stage
const morningSchoolGate = new Stage('早上校门口', '准备干那件事……', './三中门口.jpg',
      () => {
        window.playStage(morningClassroom);
      },
      [slotBreakfast, slotInviteZhiTea, getSlotPlayArknights()]
);

export { morningSchoolGate, morningClassroom, lunchBreak, afternoonPractice, afterSchool, backHome };

